<template>
  <view class="container">
    <HeadNav
      title="我的"
      bg="https://ucp-tcg.com:18001/mc/app/static/shnag_bg.png"
      bgSize="100%"
    />
    <view class="userInfo-bar">
      <button
        class="avatar-wrapper"
        open-type="chooseAvatar"
        @chooseavatar="onChooseAvatar"
      >
        <image
          class="avatar"
          :src="
            userInfo.avatarUrl
              ? userInfo.avatarUrl
              : 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
          "
        >
        </image>
        <text class="avatar-text" v-if="!userInfo.avatarUrl"
          >点击授权微信头像</text
        >
      </button>
      <view class="right-bar">
        <!-- <view class="userinfo-name">微信昵称</view> -->
        <view class="username-box">
          <input
            type="nickname"
            :focus="editing"
            placeholder="授权获取微信昵称"
            class="userinfo-name"
            placeholder-style="color: #fff"
            v-model="userInfo.nickName"
            :maxlength="15"
          />
          <uni-icons
            v-if="userInfo.nickName"
            type="compose"
            size="24"
            color="#fff"
            @tap="onEditNickName"
          ></uni-icons>
        </view>

        <view class="userinfo-text">注册时间：{{ userInfo?.createTime }}</view>
        <view class="userinfo-text"
          >手机号：
          <text v-if="showPhone">{{ userInfo?.phone }}</text>
          <uni-icons
            :type="showPhone ? 'eye' : 'eye-slash'"
            size="24"
            @click="toggleShowPhone"
            color="#fff"
            style="vertical-align: middle; margin-left: 10rpx"
          ></uni-icons>
        </view>
      </view>
      <view class="edit-icon" style="padding-left: 20rpx">
        <uni-icons
          type="email"
          size="28"
          color="#fff"
          @tap="onRedirect('/pages/my/notify')"
        ></uni-icons>
      </view>
    </view>
    <view class="content">
      <view class="code-bar">
        <!-- <view style="background: skyblue;height: 100rpx;">
					条形码
				</view> -->
        <image
          class="code-image"
          :src="userInfo.qrCodeUrl"
          @error="qrCodeError"
        ></image>
      </view>
      <view class="button-bar">
        <view class="button-bar-btn" @tap="onRedirect('/pages/my/my-active')">
          我的活动
        </view>

        <view class="button-bar-btn" @tap="onRedirect('/pages/my/my-store')">
          我的店铺
        </view>
        <view class="button-bar-btn" @tap="onRedirect('/pages/my/feedback')">
          问题反馈
        </view>
        <view
          class="button-bar-btn"
          @tap="
            onRedirect(
              '/pages/index/news?title=新手规则&nurl=' +
                'https://mp.weixin.qq.com/s/oosvjgjjVOzGGCdCEvu3Pg'
            )
          "
        >
          关注公众号
        </view>
        <view class="button-logout" @tap="logout" style="margin-top: 70rpx">
          退出登录
        </view>
        <official-account></official-account>
      </view>
    </view>
    <TabBar :active="3" />
  </view>
</template>

<script setup>
import HeadNav from '@/components/HeadNav'
import TabBar from '@/components/TabBar'
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
import { ref, watch } from 'vue'
import { userInfoApi, editUserInfoApi, refreshQrCodeApi } from '@/api/user'
import { uploadApi } from '@/api/common'
import { useUserStore } from '@/stores'
const userInfo = ref({})
const store = useUserStore()
const editing = ref(false)
const showPhone = ref(false)

onLoad(options => {
  getUserInfo()
})

// 防抖函数
const debounce = (func, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func(...args), delay)
  }
}

// 先定义editUserInfo函数
const editUserInfo = async params => {
  const res = await editUserInfoApi(params)
}

// 创建防抖版本的editUserInfo函数
const debouncedEditUserInfo = debounce(editUserInfo, 1000)

watch(
  () => userInfo.value.nickName,
  (newVal, oldVal) => {
    // console.log('newVal', newVal)
    // 微信名有变化
    if (newVal && oldVal) {
      // 使用防抖函数处理editUserInfo调用，避免频繁调用接口
      debouncedEditUserInfo({
        nickName: newVal
      })
    }
  }
)

const getUserInfo = async () => {
  uni.showLoading({
    title: '正在加载...'
  })
  const res = await userInfoApi({
    redirectUrl: '/pages/my/index'
  })
  userInfo.value = res.data
  // console.log('getUserInfo', res)
  uni.hideLoading()
}

const onRedirect = url => {
  uni.navigateTo({
    url: url
  })
}

//获取微信头像
const onChooseAvatar = e => {
  userInfo.value = {
    ...userInfo.value,
    avatarUrl: e.detail.avatarUrl
  }
  // console.log("eeee", e.detail);
  //头像图片持久化
  // 选择的微信头像是暂存到本地的路径，随时可能会失效，或者出现307重定向等一系列bug，所以要把头像上传的自己本地的服务器，或者本地的接口保存
  //uni.uploadFile将微信返回的临时地址转成文件流传输给后端，从而上传服务器，拿到永久地址
  uni.uploadFile({
    url: uploadApi(),
    filePath: e.detail.avatarUrl,
    name: 'file',
    header: {
      Authorization: store.token
      // 'content-type': 'multipart/form-data'
    },
    formData: {
      type: 'wxIcon'
    },
    success: uploadFileRes => {
      const uploadFileData = JSON.parse(uploadFileRes.data).data
      // console.log('uploadFileRes', uploadFileRes)
      userInfo.value = {
        ...userInfo.value,
        avatarUrl: uploadFileData.fileUrl
      }
      editUserInfo({
        avatarId: uploadFileData.id
      })
    }
  })
}

const onEditNickName = () => {
  editing.value = !editing.value
}

const toggleShowPhone = () => {
  showPhone.value = !showPhone.value
}

const logout = () => {
  store.userLogout()
  uni.reLaunch({
    url: '/pages/login/index'
  })
}

const qrCodeError = async e => {
  console.error('qrCode发生error事件，携带值为' + e.detail.errMsg)
  const res = await refreshQrCodeApi()
  userInfo.value.qrCodeUrl = res.data.qrCodeUrl
}

onShareAppMessage(res => {
  // if (res.from === 'button') {// 来自页面内分享按钮
  //   console.log(res.target)
  // }
  return {
    title: '欢迎使用共鸣对决', // 分享标题
    path: '/pages/index/index' // 分享路径
    // imageUrl: 'https://example.com/image.png', // 分享图标
  }
})
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  background-color: #f1f1ef;
  font-family: PingFangSC-Regular, sans-serif;
}

.notice-bar {
  padding: 0 16rpx;
  background-color: #45463a;
}

.userInfo-bar {
  padding: 32rpx 40rpx;
  box-sizing: border-box;
  // background-color: #45463A;
  background: url('https://ucp-tcg.com:18001/mc/app/static/shnag_bg.png')
    no-repeat center;
  background-size: cover;

  display: flex;
  // align-items: center;
  gap: 32rpx;

  // position: relative;
  .avatar-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: none;
    color: inherit;
    border: none;
    padding: 0;
    font: inherit;
    cursor: pointer;
    outline: inherit;
    // background-image: url('https://ucp-tcg.com:18001/mc/app/static/txk.png');
    // background-repeat: no-repeat;
    // background-size: cover;

    &::after {
      border: none;
    }

    .avatar-text {
      font-size: 24rpx;
      color: #fff;
      margin-top: 20rpx;
    }
  }

  .avatar {
    height: 120rpx;
    width: 120rpx;
    border-radius: 50%;
  }

  .right-bar {
    flex: 1;
    .username-box {
      display: flex;
      .userinfo-name {
        flex: 1;
        line-height: 44rpx;
        color: #fff;
        font-size: 32rpx;
      }
    }

    .userinfo-text {
      line-height: 48rpx;
      color: #beb7a9;
      font-size: 28rpx;
    }
  }
}

.content {
  // background-color: #F1F1EF;

  .code-bar {
    padding: 50rpx;
    text-align: center;

    .code-image {
      height: 240rpx;
      width: 240rpx;
    }
  }

  .button-bar {
    margin-top: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    .button-bar-btn {
      font-family: PingFangSC-Regular, sans-serif;
      background-color: #333;
      color: #fff;
      font-size: 32rpx;
      padding: 16rpx 0;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 60%;
      border-radius: 12rpx;
      margin-bottom: 40rpx;
      background-image: url('https://ucp-tcg.com:18001/mc/app/static/btn-bg2.png');
      background-repeat: no-repeat;
      background-size: contain;
    }

    .button-logout {
      font-family: PingFangSC-Regular, sans-serif;
      background-color: #e1e1e1;
      color: #333;
      font-size: 32rpx;
      padding: 16rpx 0;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 60%;
      border-radius: 12rpx;
      border: 2rpx solid #cecece;
      background-image: url('https://ucp-tcg.com:18001/mc/app/static/btn-bg1.png');
      background-repeat: no-repeat;
      background-size: contain;
    }
  }
}
</style>
